<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="700px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="上级菜单" prop="parent_id">
        <el-tree-select
          v-model="form.parent_id"
          :data="menuTree"
          :props="{ label: 'title', value: 'id', children: 'children' }"
          placeholder="请选择上级菜单"
          check-strictly
          clearable
        />
      </el-form-item>
      <el-form-item label="菜单名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入菜单名称" />
      </el-form-item>
      <el-form-item label="路由名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入路由名称" />
      </el-form-item>
      <el-form-item label="路由地址" prop="path">
        <el-input v-model="form.path" placeholder="请输入路由地址" />
      </el-form-item>
      <el-form-item label="组件路径" prop="component">
        <el-input v-model="form.component" placeholder="例如：/system/user/index" />
      </el-form-item>
      <el-form-item label="菜单图标" prop="icon">
        <el-input v-model="form.icon" placeholder="请输入图标名称" />
      </el-form-item>
      <el-form-item label="菜单类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio :value="1">目录</el-radio>
          <el-radio :value="2">菜单</el-radio>
          <el-radio :value="3">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权限标识" prop="permission">
        <el-input v-model="form.permission" placeholder="例如：users.view" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否隐藏" prop="hidden">
        <el-radio-group v-model="form.hidden">
          <el-radio :value="0">显示</el-radio>
          <el-radio :value="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否缓存" prop="keep_alive">
        <el-radio-group v-model="form.keep_alive">
          <el-radio :value="0">不缓存</el-radio>
          <el-radio :value="1">缓存</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  menuId: {
    type: Number,
    default: null,
  },
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(false)
const dialogTitle = ref('新增菜单')
const loading = ref(false)
const formRef = ref(null)

const form = reactive({
  parent_id: 0,
  title: '',
  name: '',
  path: '',
  component: '',
  icon: '',
  type: 2,
  permission: '',
  sort: 0,
  status: 1,
  hidden: 0,
  keep_alive: 0,
  remark: '',
})

const rules = {
  title: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
}

const menuTree = ref([])

// 监听对话框显示
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    if (props.menuId) {
      dialogTitle.value = '编辑菜单'
      loadMenuData()
    } else {
      dialogTitle.value = '新增菜单'
      resetForm()
    }
    loadMenuTree()
  }
})

// 监听对话框关闭
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 加载菜单数据
const loadMenuData = async () => {
  try {
    const res = await request.get(`/menus/${props.menuId}`)
    if (res.code === 200) {
      Object.assign(form, {
        parent_id: res.data.parent_id || 0,
        title: res.data.title,
        name: res.data.name || '',
        path: res.data.path || '',
        component: res.data.component || '',
        icon: res.data.icon || '',
        type: res.data.type,
        permission: res.data.permission || '',
        sort: res.data.sort || 0,
        status: res.data.status,
        hidden: res.data.hidden || 0,
        keep_alive: res.data.keep_alive || 0,
        remark: res.data.remark || '',
      })
    }
  } catch (error) {
    ElMessage.error('加载菜单数据失败')
  }
}

// 加载菜单树
const loadMenuTree = async () => {
  try {
    const res = await request.get('/menus', { params: { tree: true, status: 1 } })
    if (res.code === 200) {
      // 添加根节点
      menuTree.value = [
        { id: 0, title: '根菜单', children: res.data },
      ]
    }
  } catch (error) {
    console.error('加载菜单树失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    parent_id: 0,
    title: '',
    name: '',
    path: '',
    component: '',
    icon: '',
    type: 2,
    permission: '',
    sort: 0,
    status: 1,
    hidden: 0,
    keep_alive: 0,
    remark: '',
  })
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  resetForm()
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const url = props.menuId ? `/menus/${props.menuId}` : '/menus'
        const method = props.menuId ? 'put' : 'post'
        const response = await request[method](url, form)
        if (response.code === 200) {
          ElMessage.success(props.menuId ? '更新成功' : '创建成功')
          dialogVisible.value = false
          emit('success')
        }
      } catch (error) {
        if (error.errors) {
          ElMessage.error('验证失败，请检查输入')
        } else {
          ElMessage.error(error.message || '操作失败')
        }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped lang="scss">
</style>

